<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>商品管理</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="addProduct"
          >添加商品</el-button
        >
      </div>
      <!-- 表单 -->
      <el-form
        :inline="true"
        :rules="rules"
        :model="queryData"
        class="demo-form-inline"
      >
        <el-form-item label="价格区间">
          <el-col :span="11">
            <el-form-item prop="minPrice">
              <el-input
                v-model="queryData.minPrice"
                placeholder="最低价格"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="date2">
              <el-input
                v-model="queryData.maxPrice"
                placeholder="最高价格"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="queryData.classesId" placeholder="选择商品分类">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="toQuery">查询</el-button>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table :data="products" style="width: 100%" max-height="400">
        <el-table-column prop="id" label="商品编号"> </el-table-column>
        <el-table-column prop="name" label="商品名称"> </el-table-column>
        <el-table-column prop="price" label="商品价格">
          <template slot-scope="scope">
            <el-tag type="danger">{{ scope.row.price + " 元" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="商品描述"> </el-table-column>
        <el-table-column prop="classesId" label="商品分类">
          <template slot-scope="scope">
            <el-tag type="success">{{
              showClasses(scope.row.classesId)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              @click="editProduct(scope.row)"
              type="warning"
              plain
              size="small"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="deleteClasses(scope.row.id)"
              plain
              size="small"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 对话框 -->
    <el-dialog
      :title="isAdd ? '添加商品' : '编辑商品'"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="product"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="product.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="product.price"
            :precision="1"
            :step="0.1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="请输入商品描述"
            v-model="product.description"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="classesId">
          <el-select v-model="product.classesId" placeholder="请选择商品分类">
            <el-option
              v-for="item in classes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品图片" prop="picture">
          <el-button @click="$refs.toFile.click()">上传图片 </el-button>
          <input
            id="chkFile"
            ref="toFile"
            type="file"
            @change="toBase()"
            style="display: none"
          /><br />
          <img id="showImg" :src="src" height="200" style="margin-top: 20px" />
          <br />
          <textarea
            ref="picture"
            id="showText"
            style="display: none"
          ></textarea>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  reqAllProducts,
  reqAllClasses,
  reqAddProduct,
  reqUpdateProduct,
  reqDeleteProduct,
  reqQueryData,
} from "../api";

import { toBase64 } from "../utils";
//
export default {
  name: "Product",
  // data
  data() {
    return {
      products: [],
      dialogVisible: false,
      product: {},
      isAdd: false,
      rules: {
        minPrice: [{ min: 0, message: "区间必须为封闭区间", trigger: "blur" }],
      },
      classes: [],
      src: "",
      queryData: {},
    };
  },
  // mounted
  mounted() {
    this.initProducts();
    this.initClasses();
  },
  // methods
  methods: {
    // 查询商品信息
    toQuery() {
      if (Object.keys(this.queryData).length === 0) {
        this.$message("查询条件为空");
      } else {
        this.toQueryData();
      }
    },
    // 发送请求数据
    async toQueryData() {
      const { minPrice, maxPrice } = this.queryData;
      if (minPrice && !maxPrice) {
        this.$message("价格区间必须同时填写");
        return;
      }
      const { data } = await reqQueryData(this.queryData);
      this.products = data.items;
    },
    // 将图片转为base64
    toBase() {
      toBase64();
    },
    // 展示商品分类信息
    showClasses(item) {
      const arr = this.classes.filter((c) => c.id === item);
      if (arr.length === 0) {
        return "暂无分类信息";
      } else {
        return arr[0].name;
      }
    },
    // 请求所有商品信息
    async initProducts() {
      const { data } = await reqAllProducts();
      this.products = data.items;
    },
    // 请求所有分类信息
    async initClasses() {
      const { data } = await reqAllClasses();
      this.classes = data.items;
    },
    // 添加商品
    addProduct() {
      this.src = "";
      this.isAdd = true;
      this.product = {};
      this.dialogVisible = true;
    },
    // 编辑商品
    editProduct(item) {
      this.isAdd = false;
      this.src = item.picture;
      this.product = { ...item };
      this.dialogVisible = true;
    },
    // 提交表单
    toSubmit() {
      this.product.picture = this.$refs.picture.value;
      if (this.isAdd) {
        this.toAddProduct();
      } else {
        this.toUpdateProduct();
      }
    },
    // 提交添加商品的表单
    async toAddProduct() {
      const { success, message } = await reqAddProduct(this.product);
      if (success) {
        this.$message({
          type: "success",
          message,
        });
        this.initProducts();
        this.dialogVisible = false;
      } else {
        this.$message.error(message);
      }
    },
    // 提交更新商品信息的表单
    async toUpdateProduct() {
      const { success, message } = await reqUpdateProduct(this.product);
      if (success) {
        this.$message({
          type: "success",
          message,
        });
        this.initProducts();
        this.dialogVisible = false;
      } else {
        this.$message.error(message);
      }
    },
    // 删除商品
    deleteClasses(id) {
      this.$confirm("此操作将永久删除该商品, 是否继续?", "删除商品", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { success, message } = await reqDeleteProduct(id);
          if (success) {
            this.$message({
              type: "success",
              message,
            });
            this.initProducts();
            this.dialogVisible = false;
          } else {
            this.$message.error(message);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>

<style>
</style>